package com.wy.supermarket.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.wy.supermarket.entity.Worker;
import com.wy.supermarket.repository.WorkerRepository;

@RestController
@RequestMapping("/worker")
public class WorkerController {
	@Autowired //自动装载
	private WorkerRepository workerRepository;
	
	@GetMapping("/findAll/{page}/{size}")
	public Page<Worker> findAll(@PathVariable("page") Integer page,@PathVariable("size") Integer size){
		Pageable pageable=PageRequest.of(page-1, size);
		return workerRepository.findAll(pageable);
	}
	
	@PostMapping("/addWorker")
	public String addWorker(@RequestBody Worker worker) {
		Worker result=workerRepository.save(worker);
		if(result!=null) {
			return "sucess";
		}else {
			return "error";
		}
	}
	
	@GetMapping("/findById/{wnum}")
	public Worker findById(@PathVariable("wnum") Integer wnum) {
		return workerRepository.findById(wnum).get();
	}
	
	@GetMapping("/findWorker/{wname}/{wpassword}")
	public String findWorker(@PathVariable("wname") String wname,@PathVariable("wpassword") String wpassword) { //根据姓名密码查
		Worker result=workerRepository.findByWnameAndWpassword(wname, wpassword);
		if(result!=null) {
			return "sucess";
		}else {
			return "error";
		}
	}

	
	@GetMapping("/findByName/{wname}")
//	public List<Worker> findByWname(@PathVariable("wname") String wname) {  //普通查询
//		return workerRepository.findByWname(wname);
//	}
	
	public List<Worker> findByWnameLike(@PathVariable("wname") String wname) { //模糊查询
		return workerRepository.findByWnameLike("%"+wname+"%");
	}
	
	@PutMapping("/updateWorker")
	public String updateWorker(@RequestBody Worker worker) {
		Worker result=workerRepository.save(worker);
		if(result!=null) {
			return "sucess";
		}else {
			return "error";
		}
	}
	
	@DeleteMapping("/deleteById/{wnum}")
	public Worker deleteById(@PathVariable("wnum") Integer wnum) {
		workerRepository.deleteById(wnum);
		return null;
	}

}
